package com.caul.demo.hadoop.mapreduce.join;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.filecache.ClientDistributedCacheManager;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;

import java.io.IOException;

/**
 * Created by sdliang on 2018/4/9.
 */
public class JoinMapper extends Mapper<LongWritable, Text, Text, JoinBean> {

  private static final String ORDER_START = "order";
  private static final String PROFILE_START = "profile";

  private static int type;

  @Override
  protected void setup(Context context) throws IOException, InterruptedException {
    FileSplit fileSplit = (FileSplit) context.getInputSplit();
    String fileName = fileSplit.getPath().getName();
    if (fileName.startsWith(ORDER_START)) {
      type = JoinBean.FILE_ORDER;
    } else if (fileName.startsWith(PROFILE_START)) {
      type = JoinBean.FILE_PROFILE;
    }
  }

  @Override
  protected void map(LongWritable key, Text value, Context context)
      throws IOException, InterruptedException {
    String[] split = value.toString().split(":");
    JoinBean bean = new JoinBean();
    switch (type) {
      case JoinBean.FILE_ORDER:
        bean.set(split[1],split[0],type);
        break;
      case JoinBean.FILE_PROFILE:
        String[] split2 = split[1].split(",");
        bean.set(split[0],split2[0],split2[1],split2[2],type);
        break;
      default:
        break;
    }
    context.write(new Text(bean.getUid()), bean);
  }
}
